<template>
  <el-dialog
    title="坞修项目维护"
    :visible="dialogFlag"
    width="1000px"
    append-to-body
    :destroy-on-close="true"
    :close-on-click-modal="false"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <div class="grid-2">
        <el-form-item
          label-position="right"
          label="坞修项目(中文):"
          prop="projectCnName"
        >
          <el-input
            v-model="form.projectCnName"
            placeholder="请输入（200字/字符以内）"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item
          label-position="right"
          label="坞修项目(EN):"
          prop="projectEnName"
        >
          <el-input
            v-model="form.projectEnName"
            placeholder="请输入（200字/字符以内）"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label-position="right" label="类型:" prop="dataType">
          <el-radio v-model="form.dataType" label="0">坞修项目</el-radio>
          <el-radio v-model="form.dataType" label="1">说明</el-radio>
        </el-form-item>
        <el-form-item
          v-if="!hasChild"
          label-position="right"
          label="是否最末级:"
          prop="isFinalLevel"
        >
          <el-radio v-model="form.isFinalLevel" label="1">是</el-radio>
          <el-radio v-model="form.isFinalLevel" label="0">否</el-radio>
        </el-form-item>
        <div v-else></div>

        <el-form-item
          label-position="right"
          label="坞修[说明]暗提醒文字(中文):"
          prop="dockRemidingCn"
        >
          <el-input
            v-model="form.dockRemidingCn"
            placeholder="请输入"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item
          label-position="right"
          label="坞修[说明]暗提醒文字(EN):"
          prop="dockRemidingEn"
        >
          <el-input
            v-model="form.dockRemidingEn"
            placeholder="请输入"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item
          label-position="right"
          label="报价[备注]暗提醒文字(中文):"
          prop="quotationRemidingCn"
        >
          <el-input
            v-model="form.quotationRemidingCn"
            placeholder="请输入"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item
          label-position="right"
          label="报价[备注]暗提醒文字(EN):"
          prop="quotationRemidingEn"
        >
          <el-input
            v-model="form.quotationRemidingEn"
            placeholder="请输入"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item
          label-position="right"
          label="坞修[说明]显示数字软键盘"
          prop="isKeyboard"
        >
          <el-radio v-model="form.isKeyboard" label="1">是</el-radio>
          <el-radio v-model="form.isKeyboard" label="0">否</el-radio>
        </el-form-item>

        <el-form-item
          label-position="right"
          label="报价[备注]显示数字软键盘"
          prop="isKeyboardP"
        >
          <el-radio v-model="form.isKeyboardP" label="1">是</el-radio>
          <el-radio v-model="form.isKeyboardP" label="0">否</el-radio>
        </el-form-item>

        <el-form-item
          label-position="right"
          label="关联采购项目"
          prop="purchasingProjectId"
        >
          <el-cascader
            v-model="purchasingProjectId"
            :options="resumeList"
            :props="{
              value: 'id',
              label: 'projectCnName',
            }"
            clearable
            @change="handleChange"
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
      </div>

      <!--
            <el-form-item

              label-position="right"
              label="排序:"
              prop="projectSort"
            >
              <el-input
                v-model="form.projectSort"
                placeholder="请输入1-9999正整数"
                type="number"
              />
            </el-form-item>
           -->

      <template v-if="form.dataType === '0' && form.isFinalLevel === '1'">
        <div class="grid-2">
          <el-form-item
            label-position="right"
            label="单位(中文):"
            prop="projectCnUnit"
          >
            <el-input
              v-model="form.projectCnUnit"
              placeholder="请输入单位名称（100字/字符以内）"
              maxlength="100"
            />
          </el-form-item>
          <el-form-item
            label-position="right"
            label="单位(EN):"
            prop="projectEnUnit"
          >
            <el-input
              v-model="form.projectEnUnit"
              placeholder="请输入单位名称（100字/字符以内）"
              maxlength="100"
            />
          </el-form-item>
          <el-form-item
            label-position="right"
            label="所需数量:"
            prop="requireCount"
          >
            <el-input
              v-model="form.requireCount"
              placeholder="请输入数量"
              maxlength="100"
            />
          </el-form-item>
        </div>
        <h3 style="font-weight: bold">关联因素</h3>

        <el-form-item
          label-position="right"
          label="船舶类型:"
          prop="shipsTypeList"
        >
          <el-checkbox-group v-model="form.shipsTypeList">
            <el-checkbox
              v-for="dict in dict.type['ships_type']"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <div class="grid-1">
          <el-form-item label-position="right" label="船龄:" prop="boatAgeMin">
            <el-input-number
              v-model="form.boatAgeMin"
              :controls="false"
              placeholder="最小"
            ></el-input-number>
            <span>-</span>
            <el-input-number
              v-model="form.boatAgeMax"
              :controls="false"
              placeholder="最大"
            ></el-input-number>
          </el-form-item>
        </div>

        <el-form-item
          label-position="right"
          label="特检年限:"
          prop="specialInspectionAgeList"
        >
          <el-checkbox-group v-model="form.specialInspectionAgeList">
            <el-checkbox
              :key="dict.value"
              :label="dict.value"
              v-for="dict in dict.type['special_inspection_age']"
              >{{ dict.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label-position="right" label="船长（米）:" prop="">
          <el-radio-group
            v-model="boatTotalLength"
            @input="boatTotalLengthChange"
          >
            <el-radio label="1">220米以上（含220米）</el-radio>
            <el-radio label="0">220米以下</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label-position="right"
          label="检查类型:"
          prop="inspectionType"
        >
          <el-radio-group v-model="form.inspectionType">
            <el-radio
              :key="dict.value"
              :label="dict.value"
              v-for="dict in dict.type['inspection_type']"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="membershipLevel"
          label="会员等级:"
          label-position="right"
        >
          <el-radio
            v-model="form.membershipLevel"
            v-for="item in memberInfo"
            :key="item.memberCode"
            :label="item.memberCode"
          >
            {{ item.memberName }}
          </el-radio>
        </el-form-item>

        <!-- *** -->
        <h3 style="font-weight: bold">说明列取值及计算逻辑</h3>

        <el-form-item label-position="right" label="请选择方式:" prop="">
          <el-radio-group v-model="form.repairCalculateBo.calculdateTypeRemark">
            <el-radio
              :key="dict.value"
              :label="dict.value"
              v-for="dict in dict.type['calculdate_type']"
            >
              {{ dict.label }}
            </el-radio>
            <el-radio label=""> 无 </el-radio>
          </el-radio-group>
        </el-form-item>

        <template
          v-if="
            form.repairCalculateBo.calculdateTypeRemark === 'calculdate_type_1'
          "
        >
          <el-form-item label-position="right" label="请选择计算公式:" prop="">
            <div class="flexsc">
              <div class="flexsc">
                <el-popover placement="top-start" trigger="click" :width="800">
                  <div slot="reference" class="operator">说明</div>

                  <el-input
                    class="input"
                    placeholder="输入关键词过滤"
                    prefix-icon="el-icon-search"
                    v-model="treeFilter"
                    size="mini"
                    clearable
                  ></el-input>
                  <vl-tree
                    ref="tree"
                    :data="selectTreeData"
                    :props="{
                      value: 'repairProjectId',
                      label: 'projectNameCn',
                      children: 'repairProjectWebVoList',
                    }"
                    :filter-method="filterMethod"
                    @node-click="
                      (data, node, e) =>
                        nodeClickFormula(
                          data,
                          node,
                          e,
                          'remark',
                          'formulaListRemark'
                        )
                    "
                  />
                </el-popover>
              </div>

              <div class="flexsc">
                <el-popover placement="top-start" trigger="click" :width="800">
                  <div slot="reference" class="operator">数量</div>

                  <el-input
                    class="input"
                    placeholder="输入关键词过滤"
                    prefix-icon="el-icon-search"
                    v-model="treeFilter"
                    size="mini"
                    clearable
                  ></el-input>
                  <vl-tree
                    ref="tree"
                    :data="selectTreeData"
                    :props="{
                      value: 'repairProjectId',
                      label: 'projectNameCn',
                      children: 'repairProjectWebVoList',
                    }"
                    :filter-method="filterMethod"
                    @node-click="
                      (data, node, e) =>
                        nodeClickFormula(
                          data,
                          node,
                          e,
                          'count',
                          'formulaListRemark'
                        )
                    "
                  />
                </el-popover>
              </div>

              <div
                class="operator"
                v-for="(item, index) in operatorList"
                :key="index"
                @click="selectOperatorRemark(item)"
              >
                {{ item }}
              </div>

              <div
                class="operator back"
                @click="formulaListRemark.pop()"
                title="退格"
              >
                <img src="@/assets/images/back.png" alt="" height="20" />
              </div>
            </div>

            <div class="formula_res flexsc">
              <div
                class="item"
                v-for="(item, index) in formulaListRemark"
                :key="index"
              >
                {{ item.label }}
              </div>
            </div>
          </el-form-item>
        </template>

        <!-- *** -->
        <h3 style="font-weight: bold">数量列取值及计算逻辑</h3>

        <el-form-item label-position="right" label="请选择方式:" prop="">
          <el-radio-group v-model="form.repairCalculateBo.calculdateTypeCount">
            <el-radio
              :key="dict.value"
              :label="dict.value"
              v-for="dict in dict.type['calculdate_type']"
            >
              {{ dict.label }}
            </el-radio>
            <el-radio label=""> 无 </el-radio>
          </el-radio-group>
        </el-form-item>

        <template
          v-if="
            form.repairCalculateBo.calculdateTypeCount === 'calculdate_type_1'
          "
        >
          <el-form-item label-position="right" label="请选择计算公式:" prop="">
            <div class="flexsc">
              <div class="flexsc">
                <el-popover placement="top-start" trigger="click" :width="800">
                  <div slot="reference" class="operator">说明</div>

                  <el-input
                    class="input"
                    placeholder="输入关键词过滤"
                    prefix-icon="el-icon-search"
                    v-model="treeFilter"
                    size="mini"
                    clearable
                  ></el-input>
                  <vl-tree
                    ref="tree"
                    :data="selectTreeData"
                    :props="{
                      value: 'repairProjectId',
                      label: 'projectNameCn',
                      children: 'repairProjectWebVoList',
                    }"
                    :filter-method="filterMethod"
                    @node-click="
                      (data, node, e) =>
                        nodeClickFormula(
                          data,
                          node,
                          e,
                          'remark',
                          'formulaListCount'
                        )
                    "
                  />
                </el-popover>
              </div>

              <div class="flexsc">
                <el-popover placement="top-start" trigger="click" :width="800">
                  <div slot="reference" class="operator">数量</div>

                  <el-input
                    class="input"
                    placeholder="输入关键词过滤"
                    prefix-icon="el-icon-search"
                    v-model="treeFilter"
                    size="mini"
                    clearable
                  ></el-input>
                  <vl-tree
                    ref="tree"
                    :data="selectTreeData"
                    :props="{
                      value: 'repairProjectId',
                      label: 'projectNameCn',
                      children: 'repairProjectWebVoList',
                    }"
                    :filter-method="filterMethod"
                    @node-click="
                      (data, node, e) =>
                        nodeClickFormula(
                          data,
                          node,
                          e,
                          'count',
                          'formulaListCount'
                        )
                    "
                  />
                </el-popover>
              </div>

              <div
                class="operator"
                v-for="(item, index) in operatorList"
                :key="index"
                @click="selectOperatorCount(item)"
              >
                {{ item }}
              </div>

              <div
                class="operator back"
                @click="formulaListCount.pop()"
                title="退格"
              >
                <img src="@/assets/images/back.png" alt="" height="20" />
              </div>
            </div>

            <div class="formula_res flexsc">
              <div
                class="item"
                v-for="(item, index) in formulaListCount"
                :key="index"
              >
                {{ item.label }}
              </div>
            </div>
          </el-form-item>
        </template>
      </template>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <div>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  getMemberInfo,
  addRepairProject,
  editRepairProject,
  getRepairProject,
  getRepairInfo,
} from "@/api/system/repairProject";
import { listPurchasingProject } from "@/api/system/purchasingProject";

export default {
  name: "add",
  dicts: [
    "ships_type",
    "special_inspection_age",
    "inspection_type",
    "calculdate_type",
  ],
  model: {
    prop: "modelvalue",
    event: "change",
  },
  props: {
    modelvalue: {
      type: Boolean,
      default: false,
    },
    projectParent: {
      type: Number,
      default: null,
    },
    dialogType: {
      type: String,
      default: "add",
    },
    editId: {
      type: Number,
      default: null,
    },
    hasChild: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogFlag: this.modelvalue,

      // 表单参数
      form: {
        boatAgeMax: undefined,
        boatAgeMin: undefined,
        boatTotalLengthMax: undefined,
        boatTotalLengthMin: undefined,
        membershipLevel: undefined,
        projectCnName: undefined,
        projectCnUnit: undefined,
        projectEnName: undefined,
        projectEnUnit: undefined,
        // projectSort: undefined,
        shipsTypeList: [],
        specialInspectionAgeList: [],
        dataType: "0",
        isFinalLevel: "0",
        repairCalculateBo: {
          calculdateFormulasRemark: "",
          calculdateTypeRemark: "",
          calculdateFormulasCount: "",
          calculdateTypeCount: "",
          // calculdateValueRemark: "",
          // calculdateValueRemarkName: "",
          // calculdateValueCount: "",
          // calculdateValueCountName: "",
        },
      },
      // 表单校验
      rules: {
        requireCount: [
          {
            pattern: /^\d{0,8}(\.\d{1,2})?$/,
            message: "请输入0-8位整数，0-2位小数",
            trigger: "blur",
          },
        ],
        projectCnName: [
          { required: true, message: "请输入坞修项目名称", trigger: "blur" },
        ],
        projectEnName: [
          {
            required: true,
            message: "请输入坞修项目(EN)名称",
            trigger: "blur",
          },
        ],
        projectCnUnit: [
          { required: true, message: "请输入单位", trigger: "blur" },
        ],
        projectEnUnit: [
          { required: true, message: "请输入单位(EN)", trigger: "blur" },
        ],
      },
      boatTotalLength: "",
      memberInfo: [],
      selectTreeData: [],
      treeFilter: "",
      operatorList: [
        "+",
        "-",
        "*",
        "/",
        "(",
        ")",
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        ".",
      ],
      submitLoading: false,

      formulaListRemark: [], // 说明列 公式
      formulaListCount: [], // 数量列 公式

      // 采购列表数据
      resumeList: [],
      purchasingProjectId: null,
    };
  },
  created() {
    this.form.projectParent = this.projectParent;
    this.getMemberInfo();
    this.getTree();
    this.getListPurchasingProject();

    if (this.dialogType === "edit") {
      this.getDetail();
    }
  },
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val);
    },
    "form.repairCalculateBo.calculdateTypeRemark"(n) {
      if (!n) {
        this.form.repairCalculateBo.calculdateValueRemarkName = "";
        this.formulaListRemark = [];
      }
    },
    "form.repairCalculateBo.calculdateTypeCount"(n) {
      if (!n) {
        this.form.repairCalculateBo.calculdateValueCountName = "";
        this.formulaListCount = [];
      }
    },
  },
  methods: {
    /** 查询采购项目列表 */
    getListPurchasingProject() {
      listPurchasingProject({
        largeCategoryId: null,
        projectName: "",
        ignoreId: null,
      })
        .then((response) => {
          this.resumeList = this.handleTree(
            response.data,
            "id",
            "projectParent"
          );
          // console.log(this.resumeList);
        })
        .catch(() => {});
    },
    handleChange(value) {
      console.log(value);
      this.form.purchasingProjectId = value.length
        ? value[value.length - 1]
        : null;
    },
    getTree() {
      getRepairInfo().then(({ data }) => {
        this.selectTreeData = data;
      });
    },

    // 详情
    getDetail() {
      getRepairProject(this.editId).then(({ data }) => {
        data.shipsTypeList = data.shipsTypeList || [];
        data.specialInspectionAgeList = data.specialInspectionAgeList || [];
        data.repairCalculateBo = data.repairCalculateBo || {
          calculdateFormulasRemark: "",
          calculdateTypeRemark: "",
          calculdateFormulasCount: "",
          calculdateTypeCount: "",
        };

        const calculdateFormulasRemarkJson =
          data.repairCalculateBo?.calculdateFormulasRemarkJson || [];
        calculdateFormulasRemarkJson.forEach((item) => {
          item.computeValue = 1;
        });
        this.formulaListRemark = calculdateFormulasRemarkJson;

        const calculdateFormulasCountJson =
          data.repairCalculateBo?.calculdateFormulasCountJson || [];
        calculdateFormulasCountJson.forEach((item) => {
          item.computeValue = 1;
        });
        this.formulaListCount = calculdateFormulasCountJson;

        if (data.boatAgeMax === null) {
          data.boatAgeMax = undefined;
        }

        if (data.boatAgeMin === null) {
          data.boatAgeMin = undefined;
        }

        if (
          data.boatTotalLengthMax === null &&
          data.boatTotalLengthMin === 220
        ) {
          this.boatTotalLength = "1";
        }
        if (
          data.boatTotalLengthMax === 220 &&
          data.boatTotalLengthMin === null
        ) {
          this.boatTotalLength = "0";
        }

        this.form = data;
      });
    },

    // 取消按钮
    cancel() {
      this.$emit("change", false);
    },

    // 会员等级获取
    getMemberInfo() {
      getMemberInfo().then(({ data }) => {
        this.memberInfo = data;
      });
    },

    selectOperatorRemark(val) {
      this.formulaListRemark.push({
        label: val,
        value: `{${val}}`,
        computeValue: val,
      });
    },

    selectOperatorCount(val) {
      this.formulaListCount.push({
        label: val,
        value: `{${val}}`,
        computeValue: val,
      });
    },

    // 船长（米）
    boatTotalLengthChange(val) {
      // console.log(val, "====");
      if (val === "1") {
        this.form.boatTotalLengthMax = null;
        this.form.boatTotalLengthMin = 220;
      }
      if (val === "0") {
        this.form.boatTotalLengthMax = 220;
        this.form.boatTotalLengthMin = null;
      }
    },

    // 点击节点 公式
    nodeClickFormula(data, node, e, type, list) {
      // console.log(data, node, e, type);
      const obj = {
        count: "数量",
        remark: "说明",
      };
      this[list].push({
        label: `${data.projectName}[${obj[type]}]`,
        value: `{${data.repairProjectId}:${type}}`,
        computeValue: 1,
      });

      // console.log(this[list]);
    },
    // 筛选
    filterMethod(query, node) {
      return node.projectNameCn.includes(query);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form));

          // 是最末级 && 配置公式计算
          // 说明
          if (
            params.isFinalLevel === "1" &&
            params.repairCalculateBo.calculdateTypeRemark ===
              "calculdate_type_1"
          ) {
            const str = this.formulaListRemark
              .map((item) => item.computeValue)
              .join("");
            try {
              eval(str);
            } catch (error) {
              this.$message.warning("计算公式有误，请修改后重试");
              return;
            }

            // console.log(str, " >> str");

            params.repairCalculateBo.calculdateFormulasRemark =
              this.formulaListRemark.map((item) => item.value).join("");
          } else if (
            // 数量
            params.isFinalLevel === "1" &&
            params.repairCalculateBo.calculdateTypeCount === "calculdate_type_1"
          ) {
            const str = this.formulaListCount
              .map((item) => item.computeValue)
              .join("");
            try {
              eval(str);
            } catch (error) {
              this.$message.warning("计算公式有误，请修改后重试");
              return;
            }

            console.log(str, " >> str");

            params.repairCalculateBo.calculdateFormulasCount =
              this.formulaListCount.map((item) => item.value).join("");
          } else {
            delete params.repairCalculateBo;
          }

          // console.log(params);
          // return;

          this.submitLoading = true;
          if (this.form.id) {
            editRepairProject(params)
              .then((response) => {
                this.submitLoading = false;
                this.$modal.msgSuccess("操作成功");
                this.$emit("change", false);
                this.$emit("getList");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          } else {
            addRepairProject(params)
              .then((response) => {
                this.submitLoading = false;
                this.$modal.msgSuccess("操作成功");
                this.$emit("change", false);
                this.$emit("getList");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.vl-tree {
  margin-top: 10px;
}
::v-deep .vl-tree__expand-icon {
  margin-right: 15px;
}
.operator {
  display: inline-block;
  padding: 0 20px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  margin-right: 5px;
  line-height: 30px;
  height: 30px;
  border-radius: 3px;
  display: flex;
  align-items: center;
  margin-bottom: 3px;

  &:active {
    transform: translateY(1px);
  }
}

.el-input-number {
  width: 173px;
}

.grid-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  column-gap: 20px;
}

.formula_res {
  gap: 5px;
  margin-top: 15px;
  .item {
    border-bottom: 1px solid #606266;
    min-width: 20px;
    display: grid;
    justify-content: center;
    line-height: 1;
    cursor: default;
    &:hover {
      color: #999;
    }
  }
}
</style>
